package com.caissa.framework.starter.autoconfigure.log;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.turbo.MatchingFilter;
import ch.qos.logback.core.spi.FilterReply;
import com.dianping.cat.Cat;
import org.slf4j.MDC;
import org.slf4j.Marker;

import java.lang.reflect.Field;

/**
 * Description:
 * User: wangwei
 * Date: 2021-04-21 10:32 上午
 */
public class CatMDCFilter extends MatchingFilter {

    public static final String CAT_MSG_ID = "CAT_MSG_ID";
    public static final String S_INIT = "s_init";

    @Override
    public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) {

        if (!catInit(logger)) {
            return FilterReply.NEUTRAL;
        }

        String currentMessageId = Cat.getCurrentMessageId();

        if (currentMessageId == null) {
            MDC.remove(CAT_MSG_ID);
        } else {
            MDC.put(CAT_MSG_ID, currentMessageId);
        }

        return FilterReply.NEUTRAL;
    }

    private boolean catInit(Logger logger) {
        try {
            Field sinit = Cat.class.getDeclaredField(S_INIT);
            sinit.setAccessible(true);
            return sinit.getBoolean(Cat.getInstance());
        } catch (Exception e) {
            logger.warn("cat msg id 植入日志MDC失败", e);
            return false;
        }
    }
}

